import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../../core/api_response.dart';
import '../../models/user.dart';
import '../../models/auth_token.dart';
import '../../models/login_request.dart';
import '../auth_repository.dart';

class MockAuthRepository implements AuthRepository {
  static const String _tokenKey = 'mock_auth_token';
  static const String _userKey = 'mock_auth_user';
  
  // 模拟用户数据
  final Map<String, Map<String, dynamic>> _mockUsers = {
    'test@example.com': {
      'id': 1,
      'username': 'test@example.com',
      'email': 'test@example.com',
      'password': '123456',
      'displayName': '测试用户',
      'partnerName': '亲爱的',
      'relationshipStartDate': '2024-01-01T00:00:00Z',
      'createdAt': '2024-01-01T00:00:00Z',
      'updatedAt': '2024-01-01T00:00:00Z',
    },
    'admin': {
      'id': 2,
      'username': 'admin',
      'email': 'admin@example.com',
      'password': 'admin123',
      'displayName': '管理员',
      'partnerName': '小宝贝',
      'relationshipStartDate': '2023-12-25T00:00:00Z',
      'createdAt': '2023-12-25T00:00:00Z',
      'updatedAt': '2023-12-25T00:00:00Z',
    },
  };

  @override
  Future<ApiResponse<LoginResponse>> login(LoginRequest request) async {
    print('🔐 [MOCK_AUTH] 模拟登录: ${request.username}');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 500));
    
    final userData = _mockUsers[request.username];
    
    if (userData == null || userData['password'] != request.password) {
      return ApiResponse.error(
        error: '用户名或密码错误',
        statusCode: 401,
      );
    }
    
    // 创建模拟 Token
    final token = AuthToken(
      accessToken: 'mock_access_token_${DateTime.now().millisecondsSinceEpoch}',
      refreshToken: 'mock_refresh_token_${DateTime.now().millisecondsSinceEpoch}',
      expiresAt: DateTime.now().add(const Duration(hours: 24)),
    );
    
    // 创建用户对象
    final user = User.fromJson(userData);
    
    // 创建登录响应
    final loginResponse = LoginResponse(
      token: token,
      user: user,
      message: '登录成功',
    );
    
    // 保存到本地存储
    await saveToken(token);
    await saveUser(user);
    
    print('✅ [MOCK_AUTH] 模拟登录成功: ${user.username}');
    return ApiResponse.success(
      data: loginResponse,
      message: '登录成功',
    );
  }

  @override
  Future<ApiResponse<User>> register(RegisterRequest request) async {
    print('📝 [MOCK_AUTH] 模拟注册: ${request.username}');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 800));
    
    // 检查用户是否已存在
    if (_mockUsers.containsKey(request.username) || 
        _mockUsers.values.any((u) => u['email'] == request.email)) {
      return ApiResponse.error(
        error: '用户名或邮箱已存在',
        statusCode: 409,
      );
    }
    
    // 验证密码匹配
    if (request.password != request.confirmPassword) {
      return ApiResponse.error(
        error: '两次输入的密码不一致',
        statusCode: 422,
      );
    }
    
    // 创建新用户
    final userId = _mockUsers.length + 1;
    final userData = {
      'id': userId,
      'username': request.username,
      'email': request.email,
      'password': request.password,
      'displayName': request.displayName ?? request.username,
      'partnerName': request.partnerName,
      'relationshipStartDate': request.relationshipStartDate?.toIso8601String(),
      'createdAt': DateTime.now().toIso8601String(),
      'updatedAt': DateTime.now().toIso8601String(),
    };
    
    _mockUsers[request.username] = userData;
    final user = User.fromJson(userData);
    
    print('✅ [MOCK_AUTH] 模拟注册成功: ${user.username}');
    return ApiResponse.success(
      data: user,
      message: '注册成功',
    );
  }

  @override
  Future<ApiResponse<void>> logout() async {
    print('🚪 [MOCK_AUTH] 模拟登出');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 300));
    
    await clearToken();
    await clearUser();
    
    print('✅ [MOCK_AUTH] 模拟登出成功');
    return ApiResponse.success(message: '登出成功');
  }

  @override
  Future<ApiResponse<void>> forgotPassword(ForgotPasswordRequest request) async {
    print('📧 [MOCK_AUTH] 模拟发送找回密码邮件: ${request.email}');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 1000));
    
    // 检查邮箱是否存在
    final userExists = _mockUsers.values.any((u) => u['email'] == request.email);
    
    if (!userExists) {
      return ApiResponse.error(
        error: '该邮箱未注册',
        statusCode: 404,
      );
    }
    
    print('✅ [MOCK_AUTH] 模拟找回密码邮件发送成功');
    return ApiResponse.success(message: '找回密码邮件已发送，请检查您的邮箱');
  }

  @override
  Future<ApiResponse<AuthToken>> refreshToken(String refreshToken) async {
    print('🔄 [MOCK_AUTH] 模拟刷新Token');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 400));
    
    // 创建新的 Token
    final token = AuthToken(
      accessToken: 'mock_access_token_${DateTime.now().millisecondsSinceEpoch}',
      refreshToken: 'mock_refresh_token_${DateTime.now().millisecondsSinceEpoch}',
      expiresAt: DateTime.now().add(const Duration(hours: 24)),
    );
    
    await saveToken(token);
    
    print('✅ [MOCK_AUTH] 模拟Token刷新成功');
    return ApiResponse.success(
      data: token,
      message: 'Token刷新成功',
    );
  }

  @override
  Future<AuthToken?> getStoredToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tokenJson = prefs.getString(_tokenKey);
      
      if (tokenJson != null) {
        final tokenMap = jsonDecode(tokenJson) as Map<String, dynamic>;
        return AuthToken.fromJson(tokenMap);
      }
      
      return null;
    } catch (e) {
      print('❌ [MOCK_AUTH] 获取存储的Token失败: $e');
      return null;
    }
  }

  @override
  Future<void> saveToken(AuthToken token) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final tokenJson = jsonEncode(token.toJson());
      await prefs.setString(_tokenKey, tokenJson);
      print('✅ [MOCK_AUTH] Token保存成功');
    } catch (e) {
      print('❌ [MOCK_AUTH] Token保存失败: $e');
    }
  }

  @override
  Future<void> clearToken() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_tokenKey);
      print('🗑️ [MOCK_AUTH] Token已清除');
    } catch (e) {
      print('❌ [MOCK_AUTH] Token清除失败: $e');
    }
  }

  @override
  Future<ApiResponse<User>> getProfile() async {
    print('👤 [MOCK_AUTH] 模拟获取用户信息');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 300));
    
    final user = await getStoredUser();
    
    if (user == null) {
      return ApiResponse.error(
        error: '用户信息未找到',
        statusCode: 404,
      );
    }
    
    print('✅ [MOCK_AUTH] 模拟获取用户信息成功: ${user.username}');
    return ApiResponse.success(
      data: user,
      message: '获取用户信息成功',
    );
  }

  @override
  Future<ApiResponse<User>> updateProfile(User user) async {
    print('✏️ [MOCK_AUTH] 模拟更新用户信息: ${user.username}');
    
    // 模拟网络延迟
    await Future.delayed(const Duration(milliseconds: 600));
    
    // 更新模拟数据
    if (_mockUsers.containsKey(user.username)) {
      _mockUsers[user.username] = user.copyWith(
        updatedAt: DateTime.now(),
      ).toJson();
    }
    
    final updatedUser = user.copyWith(updatedAt: DateTime.now());
    await saveUser(updatedUser);
    
    print('✅ [MOCK_AUTH] 模拟用户信息更新成功');
    return ApiResponse.success(
      data: updatedUser,
      message: '用户信息更新成功',
    );
  }

  @override
  Future<User?> getStoredUser() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userJson = prefs.getString(_userKey);
      
      if (userJson != null) {
        final userMap = jsonDecode(userJson) as Map<String, dynamic>;
        return User.fromJson(userMap);
      }
      
      return null;
    } catch (e) {
      print('❌ [MOCK_AUTH] 获取存储的用户信息失败: $e');
      return null;
    }
  }

  @override
  Future<void> saveUser(User user) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final userJson = jsonEncode(user.toJson());
      await prefs.setString(_userKey, userJson);
      print('✅ [MOCK_AUTH] 用户信息保存成功: ${user.username}');
    } catch (e) {
      print('❌ [MOCK_AUTH] 用户信息保存失败: $e');
    }
  }

  @override
  Future<void> clearUser() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_userKey);
      print('🗑️ [MOCK_AUTH] 用户信息已清除');
    } catch (e) {
      print('❌ [MOCK_AUTH] 用户信息清除失败: $e');
    }
  }

  @override
  Future<bool> isLoggedIn() async {
    final token = await getStoredToken();
    final user = await getStoredUser();
    return token != null && user != null && !token.isExpired;
  }

  @override
  Future<bool> hasValidToken() async {
    final token = await getStoredToken();
    return token != null && !token.isExpired;
  }
}